package fr.ginvest.implementation;

import java.util.Collection;
import java.util.Date;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import fr.ginvest.entity.Angel;
import fr.ginvest.entity.Club;
import fr.ginvest.entity.Demande;
import fr.ginvest.entity.Demande.Etat;
import fr.ginvest.entity.DemandeAngelClub;
import fr.ginvest.interfaces.DemandeAngelClubFacadeRemote;

/**
 * Session Bean implementation class DemandeAngelClubFacade
 */
@Stateless
public class DemandeAngelClubFacade implements DemandeAngelClubFacadeRemote {

	@PersistenceContext
	protected EntityManager entityMgr;
	public DemandeAngelClubFacade() {
	}	

	public DemandeAngelClubFacade(EntityManager entityMgr) {
		this.entityMgr = entityMgr;
	}
	
    public DemandeAngelClub findDemandeAngelClubById(int id) {
        return entityMgr.find(DemandeAngelClub.class, id);
    }
    
    public void deleteDemandeAngelClub(DemandeAngelClub dac) {
    	entityMgr.remove(dac);
    }
    
    public DemandeAngelClub updateDemandeAngelClub(DemandeAngelClub dac) {
    	return entityMgr.merge(dac);
    }
    
    public DemandeAngelClub addDemandeAngelClub(DemandeAngelClub dac) {
    	entityMgr.persist(dac);
		return dac;
    }

	@SuppressWarnings("unchecked")
	@Override
	public Collection<DemandeAngelClub> listDemandeByClub(Club club) {
		final String queryString = "select d from DemandeAngelClub d where d.destination=:club and d.etat=:etat";
		Query query = entityMgr.createQuery(queryString);
		query.setParameter("club", club);
		query.setParameter("etat", Etat.NON_TRAITE);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<DemandeAngelClub> listEnvDemandeByClub(Angel angel) {
		final String queryString = "select d from DemandeAngelClub d where d.origine=:angel";
		Query query = entityMgr.createQuery(queryString);
		query.setParameter("angel", angel);
		return query.getResultList();
	}
	
	@Override
	public void acceptDemande(DemandeAngelClub dac) {
		dac.setEtat(Demande.Etat.ACCEPTE);
		dac.setDateTraite(new Date());
		entityMgr.merge(dac);
		
		Angel a = dac.getOrigine();
		Club c = dac.getDestination();
		c.addMembre(a);
		entityMgr.merge(c);
		
	}
}
